<!--用户管理组件-->
<script setup>
import { ref } from 'vue';
import { useStore } from 'vuex';
import UserDialog from '../views/dialog/UserDialog.vue'; // 假设有一个用户对话框组件
import { ElMessage } from 'element-plus';

const store = useStore();
const dialogVisible = ref(false);
const currentUser = ref(null);
const users = ref([]);

const fetchUsers = () => {
  store.dispatch('fetchUsers').then(() => {
    ElMessage.success('用户列表已更新');
  }).catch(() => {
    ElMessage.error('获取用户列表失败');
  });
};

const showAddUserDialog = () => {
  currentUser.value = null; // 清空当前用户
  dialogVisible.value = true; // 显示对话框
};

const handleUserSubmit = (userData) => {
  if (userData.id) {
    store.dispatch('updateUser', userData).then(() => {
      ElMessage.success('用户更新成功');
      dialogVisible.value = false; // 关闭对话框
      fetchUsers(); // 刷新用户列表
    }).catch(() => {
      ElMessage.error('更新用户失败');
    });
  } else {
    store.dispatch('addUser', userData).then(() => {
      ElMessage.success('用户添加成功');
      dialogVisible.value = false; // 关闭对话框
      fetchUsers(); // 刷新用户列表
    }).catch(() => {
      ElMessage.error('添加用户失败');
    });
  }
};

const deleteUser = (userId) => {
  store.dispatch('deleteUser', userId).then(() => {
    ElMessage.success('用户删除成功');
    fetchUsers(); // 刷新用户列表
  }).catch(() => {
    ElMessage.error('删除用户失败');
  });
};

fetchUsers(); // 初始加载用户
</script>

<template>
  <div class="user-management">
    <h1>用户管理</h1>
    <el-table :data="users" style="width: 100%">
      <el-table-column prop="id" label="用户ID" />
      <el-table-column prop="name" label="用户名" />
      <el-table-column prop="role" label="角色" />
      <el-table-column label="操作">
        <template v-slot="scope">
          <el-button @click="editUser(scope.row)">编辑</el-button>
          <el-button type="danger" @click="deleteUser(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-button type="primary" @click="showAddUserDialog">添加用户</el-button>
    <UserDialog
      v-model="dialogVisible"
      :currentUser="currentUser"
      @submit="handleUserSubmit"
    />
  </div>
</template>

<style scoped>
.user-management {
  padding: 20px;
}
</style>